package com.lk.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lk.common.ErrorCode;
import com.lk.common.Result;
import com.lk.exception.BusinessException;
import com.lk.model.domain.Post;
import com.lk.model.domain.User;
import com.lk.model.request.AddCommentRequest;
import com.lk.model.request.DeletePostRequest;
import com.lk.model.request.PostAddLikeRequest;
import com.lk.model.request.PostLessLikeRequest;
import com.lk.model.vo.PostLikeVO;
import com.lk.service.PostService;
import com.lk.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Type;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/post")
public class PostController {

    @Resource
    private UserService userService;
    @Resource
    private PostService postService;

/**
 * 创建帖子
 * @param title
 * @param content
 * @param file1
 * @param file2
 * @param file3
 * @param file4
 * @return
 */
    @ApiOperation("创建帖子")
    @PostMapping("/add")
    public Result<String> addPost(
            HttpServletRequest request,
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam(value = "file1",required = false) MultipartFile file1,
            @RequestParam(value = "file2", required = false) MultipartFile file2,
            @RequestParam(value = "file3", required = false) MultipartFile file3,
            @RequestParam(value = "file4", required = false) MultipartFile file4) {

        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Post post = new Post();

        Long userId = loginUser.getId();
        String realAvatarUrl = userService.getRealAvatarUrl(userId);
        String username = loginUser.getUsername();

        // 保存图片文件
        List<MultipartFile> files = new ArrayList<>();
        if (file1 != null) files.add(file1);
        if (file2 != null) files.add(file2);
        if (file3 != null) files.add(file3);
        if (file4 != null) files.add(file4);
        if (!files.isEmpty()) {
            //用数组存放图片路径
            ArrayList<String> arrayList = new ArrayList<>();

            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    //存放图片，获取路径
                    String path = postService.saveFile(file, request);
                    arrayList.add(path);
                }
            }
            Gson gson = new Gson();
            //图片路径
            String jsonPath = gson.toJson(arrayList);
            post.setImages(jsonPath);
        }

        // 保存帖子信息
        post.setTitle(title);
        post.setContent(content);
        post.setUserId(userId);
        post.setUserName(username);
        post.setAvatarUrl(realAvatarUrl);

        int i = postService.addPost(post);
        if (i > 0) {
            return Result.success("帖子创建成功");
        }else {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 查询帖子列表
     * @param request
     * @return
     */
    @ApiOperation("查询所有帖子列表")
    @GetMapping("/list")
    public Result<List<Post>> listPost(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }

        List<Post> posts = postService.selectAll();
        return Result.success(posts);
    }


    /**
     * 点赞修改数据
     * @param request
     * @param postAddLikeRequest
     * @return
     */
    @ApiOperation("点赞帖子")
    @PostMapping("/addLike")
    public Result<PostLikeVO> addLike(HttpServletRequest request, @RequestBody PostAddLikeRequest postAddLikeRequest) {

        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if (postAddLikeRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long loginUserId = loginUser.getId();
        Long postId = postAddLikeRequest.getPostId();
        int b = postService.addLike(postId, loginUserId);

        PostLikeVO postLikeVO = new PostLikeVO();
        postLikeVO.setFollowsNum(b);
        postLikeVO.setInfo("点赞成功");
        return Result.success(postLikeVO);
    }


    /**
     * 取消点赞修改数据
     * @param request
     * @param postLessLikeRequest
     * @return
     */
    @ApiOperation("取消点赞帖子")
    @PostMapping("/lessLike")
    public Result addLike(HttpServletRequest request, @RequestBody PostLessLikeRequest postLessLikeRequest) {

        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if (postLessLikeRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long loginUserId = loginUser.getId();
        Long postId = postLessLikeRequest.getPostId();
        int b = postService.lessLike(postId, loginUserId);

        PostLikeVO postLikeVO = new PostLikeVO();
        postLikeVO.setFollowsNum(b);
        postLikeVO.setInfo("取消点赞成功");
        return Result.success(postLikeVO);
    }


    /**
     * 根据id获取评论详情
     *
     * @param request
     * @param postId
     * @return
     */
    @GetMapping("/comment")
    @ApiOperation("根据帖子id获取评论详情")
    public Result<String> commentDetail(HttpServletRequest request,Long postId){

        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        String commentDetail = postService.getCommentDetail(postId);

        return Result.success(commentDetail);
    }


    /**
     * 添加评论
     *
     * @param request
     * @param addCommentRequest
     * @return
     */
    @PostMapping("/addComment")
    @ApiOperation("添加评论")
    public Result addComment(HttpServletRequest request, @RequestBody AddCommentRequest addCommentRequest) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if (addCommentRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 基本参数校验
        Long postId = addCommentRequest.getPostId();
        String commentContent = addCommentRequest.getContent();
        if (postId == null || commentContent == null || commentContent.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 构建评论数据
        Map<String, Object> commentData = new HashMap<>();
        commentData.put("userId", loginUser.getId());
        commentData.put("content", commentContent.trim());
        commentData.put("createTime", new Date());
        commentData.put("userName", loginUser.getUsername());
        commentData.put("avatarUrl", loginUser.getAvatarUrl());


        // 配置Gson日期格式
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();

        try {
            // 1. 获取现有评论数据
            String commentDetail = postService.getCommentDetail(postId);
            List<Map<String, Object>> commentList = new ArrayList<>();

            // 2. 解析现有评论（如果有）
            if (commentDetail != null && !commentDetail.isEmpty()) {
                Type listType = new TypeToken<List<Map<String, Object>>>(){}.getType();
                List<Map<String, Object>> existingComments = gson.fromJson(commentDetail, listType);
                if (existingComments != null) {
                    commentList.addAll(existingComments);
                }
            }

            //获取现有评论个数
            int size = commentList.size();
            commentData.put("id",size+1);

            // 3. 添加新评论
            commentList.add(commentData);

            // 4. 生成新的JSON数组
            String updatedJson = gson.toJson(commentList);

            //获取评论个数
            size = commentList.size();

            // 5. 更新到数据库
            postService.updateCommentNum(postId, size);

            int result = postService.addComment(postId, updatedJson);

            return result > 0 ? Result.success("评论成功") : Result.error(ErrorCode.SYSTEM_ERROR);

        } catch (JsonSyntaxException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "评论数据解析失败");
        }
    }

    /**
     * 根据id删除帖子
     *
     * @param request
     * @param deletePostRequest
     * @return
     */
    @ApiOperation("根据帖子id删除帖子")
    @PostMapping("/delete")
    public Result deletePost(HttpServletRequest request, @RequestBody DeletePostRequest deletePostRequest){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }

        int result = postService.deletePost(deletePostRequest.getPostId());
        if (result > 0){
            return Result.success("删除成功");
        }else {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
    }

}
